// pages/record/meal-list.js
const { get } = require('../../utils/request');
const { formatDate, formatTime } = require('../../utils/util');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        startDate: '',
        endDate: '',
        records: [],
        page: 1,
        pageSize: 10,
        hasMore: true,
        loading: false,
        stats: {
            totalCount: 0,
            totalCalories: 0,
            avgCalories: 0
        },
        typeIcons: {
            '早餐': '/images/breakfast.png',
            '午餐': '/images/lunch.png',
            '晚餐': '/images/dinner.png',
            '加餐': '/images/snack.png'
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 初始化日期范围为最近7天
        const end = new Date();
        const start = new Date();
        start.setDate(start.getDate() - 6);
        
        this.setData({
            startDate: formatDate(start),
            endDate: formatDate(end)
        });
        
        this.loadRecords(true);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.resetAndLoad().then(() => {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.loadRecords();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    // 选择开始日期
    onStartDateChange(e) {
        this.setData({
            startDate: e.detail.value
        });
        this.resetAndLoad();
    },

    // 选择结束日期
    onEndDateChange(e) {
        this.setData({
            endDate: e.detail.value
        });
        this.resetAndLoad();
    },

    // 重置分页并重新加载数据
    resetAndLoad() {
        this.setData({
            page: 1,
            records: [],
            hasMore: true
        });
        this.loadRecords(true);
    },

    // 加载记录数据
    async loadRecords(showLoading = false) {
        if (this.data.loading || !this.data.hasMore) return;

        try {
            if (showLoading) {
                wx.showLoading({
                    title: '加载中...',
                });
            }

            this.setData({ loading: true });

            const { startDate, endDate, page, pageSize } = this.data;
            const response = await get('/records/diet', {
                startDate,
                endDate,
                page,
                pageSize
            });

            // 处理记录数据
            const formattedRecords = response.records.map(record => ({
                ...record,
                formattedDate: formatTime(new Date(record.date)),
                foods: record.foods.map(food => ({
                    ...food,
                    amount: `${food.amount}*${food.unit}`
                }))
            }));

            // 计算统计数据
            const totalCalories = formattedRecords.reduce((sum, record) => sum + record.totalCalories, 0);
            const avgCalories = formattedRecords.length > 0 ? (totalCalories / formattedRecords.length).toFixed(1) : 0;

            // 更新页面数据
            this.setData({
                records: page === 1 ? formattedRecords : [...this.data.records, ...formattedRecords],
                stats: {
                    totalCount: formattedRecords.length,
                    totalCalories: totalCalories.toFixed(1),
                    avgCalories
                },
                hasMore: formattedRecords.length === pageSize,
                page: page + 1
            });
        } catch (error) {
            console.error('加载记录失败:', error);
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            });
        } finally {
            this.setData({ loading: false });
            if (showLoading) {
                wx.hideLoading();
            }
        }
    },

    // 预览图片
    previewImage(e) {
        const { current, urls } = e.currentTarget.dataset;
        wx.previewImage({
            current,
            urls
        });
    }
})